<template>
  <div class="adoptCategory tree-page">
    <search-block>
      <template slot="button">
        <el-button @click="doFilter">查询</el-button>
        <el-button type="primary" @click="addCategory()">添加类别</el-button>
      </template>
      <el-form inline :model="search" label-width="100px" @submit.native.prevent>
        <el-form-item label="类别名称:">
          <el-input v-model="search.name" clearable></el-input>
        </el-form-item>
      </el-form>
    </search-block>
    <div class="category-tree-block tree-block tree-page-block">
      <el-tree
        ref="tree"
        :key="treeKey"
        :data="categoryData"
        accordion
        node-key="cateCode"
        :filter-node-method="filterNode"
        :props="{ label: 'cateName', children: 'children' }"
        lazy
        :load="loadChild">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span class="tree-node-label">{{ node.label }}</span>
        <span class="tree-node-btn">
          <el-link
            v-if="node.level < 2"
            :underline="false"
            type="primary"
            @click="() => addCategory(node)">
            添加类别项
          </el-link>
          <el-link
              :underline="false"
              type="primary"
              @click="() => editCategory(node)">
            编辑
          </el-link>
          <el-popconfirm
              title="是否确认删除该类别项？"
              @confirm="delCategory(data)">
            <el-link
                disabled
                slot="reference"
                :underline="false"
                type="danger">
              删除
            </el-link>
          </el-popconfirm>
        </span>
      </span>
      </el-tree>
    </div>
    <y-form
      :key="refreshKey"
      ref="yForm"
      v-model="forms.formModel"
      :visible.sync="forms.showForm"
      :title="forms.formTypeTitle[forms.formsType]"
      width="50%"
      destroy-on-close
      :formAttrs="forms.formAttrs"
      :columns="getFormColumns()"
      @close="refreshKey+=2"
      @ensure="ensureModel">
      <template slot="cateLevel">
        <el-input v-model="forms.formModel.cateLevel" disabled style="width: 50px;margin-right: 10px"></el-input>级
      </template>
      <template slot="picUrl">
        <y-upload-img
          :url="forms.formModel.picUrl ? [{
            url: forms.formModel.picUrl,
            id: forms.formModel.attachmentId
          }] : []"
          value-type="ObjectArray"
          @update="updateModel"
          re-upload
          business-sys-module-code="ADOPT_CATEGORY"
          :limit="1">
        </y-upload-img>
      </template>
    </y-form>
  </div>
</template>

<script>
export default {
  name: "adoptCategory",
  data(){
    return{
      search:{
        name: ''
      },
      categoryData: [],
      refreshKey: 0,
      treeKey: 1,
      filterTag: false,
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加类别',
          'EDIT': '编辑类别'
        },
        currentForm: null,
        formModel: {
          id: '',
          cateCode: '',
          cateName: '',
          catePcode: null,
          catePname: '',
          cateLevel: 1,
          orderNum: '',
          attachmentId: '',
          picUrl: ''
        },
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            cateCode: [
              {required: true, message: "请输入类别编码", trigger: "blur"},
              {
                validator: (rule, value, callback) => {
                  this.$$validateCode(
                    this.$api.adopt.validateCateCode,
                    {
                      id: this.forms.formModel.id,
                      cateCode: value
                    }, callback);
                },
                trigger: 'blur'
              }
            ],
            cateName: [{required: true, message: "请选择类别名称", trigger: "blur"}],
            picUrl: [{required: true, message: "请选择图片", trigger: "change"}]
          }
        }
      }
    }
  },
  methods:{
    refresh(){
      this.treeKey+=2;
      this.filterTag = true;
    },
    showYForm(){
      this.forms.showForm = true;
    },
    getFormColumns(){
      return [
        {
          label: "上一级类别",
          prop: "catePname",
          comp:{
            compType: 'input',
            attrs:{
              disabled: true
            }
          }
        },
        {
          label: "类别编码",
          prop: "cateCode",
          comp:{
            compType: 'input',
            attrs:{
              clearable: true,
              disabled: this.forms.formsType === "EDIT",
              maxlength: 10,
              showWordLimit: true
            }
          }
        },
        {
          label: "类别名称",
          prop: "cateName",
          comp:{
            compType: 'input',
            attrs:{
              clearable: true,
              maxlength: 30,
              showWordLimit: true
            }
          }
        },
        {
          label: "当前级别",
          prop: "cateLevel",
          template: true
        },
          //TODO 暂时屏蔽图片上传
        /*{
          label: "图标",
          prop: "picUrl",
          vIf: this.forms.formModel.cateLevel == '1',
          template: true
        },*/
        {
          label: "排序",
          prop: "orderNum",
          comp:{
            compType: 'input-number',
          }
        }
      ]
    },
    doFilter(){
      this.$refs.tree.filter(this.search.name);
    },
    filterNode(value, data){
      if (!value) return true;
      return data.cateName.indexOf(value) >= 0
    },
    loadChild(node,resolve){
      this.$yAxios({
        url: this.$api.adopt.getAdoptCategoryChild,
        data:{
          catePcode: node.data.cateCode || null
        }
      },info => {
        if(this.filterTag){
          this.filterTag = false;
          this.$nextTick(() => {
            this.doFilter();
          })
        }
        resolve(info)
      }, () => {
        resolve([])
      })
    },
    validDelete(data){
      return new Promise(resolve => {
        this.$yAxios({
          url: this.$api.adopt.getAdoptCategoryChild,
          data:{
            catePcode: data.cateCode
          },
          loading: true
        },info => {
          resolve(Array.isArray(info) && !info.length)
        }, () => {
          resolve(false)
        })
      })
    },
    resetForm(data = this.forms.currentForm){
      this.forms.formModel = Object.assign({
        id: '',
        cateCode: '',
        cateName: '',
        catePcode: null,
        catePname: '',
        cateLevel: 1,
        orderNum: '',
        attachmentId: '',
        picUrl: ''
      }, data)
    },
    addCategory({level, data} = {level: 0, data: {id: '', cateName: '无'}}){
      if(level === 2){
        this.$alert('无法在2级目录下添加类别', {
          confirmButtonText: '确定'
        });
        return;
      }
      this.forms.formsType = 'ADD';
      this.forms.currentForm = data;
      this.resetForm({
        catePcode: data.cateCode || null,
        catePname: data.cateName,
        cateLevel: +level + 1
      });
      this.showYForm();
    },
    editCategory({level, data}){
      this.forms.formsType = 'EDIT';
      let pNode = this.$refs['tree'].getNode(data.catePcode || '');
      if(pNode){
        data.catePname = pNode.data.cateName;
      }
      this.forms.currentForm = data;
      this.resetForm();
      this.showYForm();
    },
    async delCategory(data){
      let deleteAble = await this.validDelete(data)
      if(!deleteAble){
        await this.$alert('无法删除包含子品种的物品种类', {
          confirmButtonText: '确定'
        });
        return;
      }
      this.$yAxios({
        url: this.$api.adopt.removeAdoptCategory,
        data:{
          ids: [data.id]
        },
        loading: true
      }, info => {
        let pArray = this.categoryData, pId = data.parentId
        if(pId){
          let PNode = this.$refs['tree'].getNode(pId);
          pArray = PNode.data.children;
        }
        //let index = pArray.indexOf(data);
        this.$refs['tree'].remove(data);
        this.$message({
          type: 'success',
          message: '删除成功'
        });
      })
    },
    updateModel({type, file}){
      switch(type) {
        case 'delete': {
          this.forms.formModel.attachmentId = '';
          this.forms.formModel.picUrl = '';
          break;
        }
        case 'edit': case 'add':{
          this.forms.formModel.attachmentId = file.id;
          this.forms.formModel.picUrl = file.name;
          this.$refs['yForm'].$refs['form'].validateField('picUrl');
          break;
        }
      }
    },
    ensureModel(form){
      let newForm, url;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
        url = this.$api.adopt.saveAdoptCategory;
      }else{
        newForm = Object.assign({}, form);
        url = this.$api.adopt.saveAdoptCategory
      }
      this.$yAxios({
        url,
        data: newForm,
        loading: true
      }, info => {
        if(info) newForm = info;
        switch(this.forms.formsType){
          case 'ADD':{
            if(this.forms.currentForm && this.forms.currentForm.id){//添加类别项
              if(!this.forms.currentForm.children){
                this.$set(this.forms.currentForm, 'children', []);
              }
              this.$refs['tree'].getNode(this.forms.currentForm).expanded = true;
              this.$refs['tree'].append(newForm, this.forms.currentForm);
            }else{//添加类别
              this.refresh();
            }
            break;
          }
          case 'EDIT':{
            Object.assign(this.forms.currentForm, newForm);
            break;
          }
        }
        this.$message({
          type: 'success',
          message: '保存成功'
        });
      })
    }
  }
}
</script>

<style scoped lang="less">
</style>